package com.liu.network.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

public class SocketService {
	// 搭建服务器端
	public static void main(String[] args) throws IOException {
		SocketService socketService = new SocketService();
		// 1、a)创建一个服务器端Socket，即SocketService
		socketService.oneServer();
	}

	public void oneServer() {
		try {
			ServerSocket server = null;
			try {
				server = new ServerSocket(6789);
				server.setSoTimeout(10 * 1000);
				// b)指定绑定的端口，并监听此端口。
				System.out.println("服务器启动成功");
				// 创建一个ServerSocket在端口5209监听客户请求
			} catch (Exception e) {
				System.out.println("没有启动监听：" + e);
				// 出错，打印出错信息
			}
			Socket socket = null;
			try {
				socket = server.accept();
				// 2、调用accept()方法开始监听，等待客户端的连接
				// 使用accept()阻塞等待客户请求，有客户
				// 请求到来则产生一个Socket对象，并继续执行
			} catch (Exception e) {
				System.out.println("Error." + e);
				// 出错，打印出错信息
			}
			InputStream is = socket.getInputStream();
			int r = 0;
			List<Byte> list = new LinkedList<Byte>();
			while ((r = is.read()) != -1) {
				list.add(Byte.valueOf((byte) r));
			}
			byte[] data = new byte[list.size()];
			for (int i = 0; i < list.size(); i++) {
				data[i] = list.get(i);
			}
			String str = new String(data);
			System.out.println("客户端传输过来的参数" + str);
			// 关闭连接
			is.close();

			OutputStream os = null;
//			List<Byte> head = new LinkedList<Byte>();
			byte[] a = hexStringToByteArray("464E4951");
			byte[] b = new byte[4];
			String response = "status:1,err_msg:Can not find %s, white list function is invaliable!";
			byte[] c = response.getBytes();
			b = (c.length+"").getBytes();
			byte[] head = new byte[4+4+c.length];
			for (int i = 0; i < a.length; i++) {
				head[i] = a[i];
//				head.add(a[i]);
			}
			for (int i = 0; i < b.length; i++) {
				head[i+4] = b[i];
//				head.add(b[i]);
			}
			for (int i = 0; i < c.length; i++) {
				head[i+8] = c[i];
//				head.add(c[i]);
			}
			try {
				os = socket.getOutputStream();
				os.write(head);
				// 关闭连接
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			socket.close(); // 关闭Socket
			server.close(); // 关闭ServerSocket
		} catch (Exception e) {// 出错，打印出错信息
			System.out.println("Error." + e);
		}
	}
	public static byte[] hexStringToByteArray(String hexStr) {
	    if(hexStr.length()%2 == 1){
	       hexStr = "0"+hexStr;
	    }
	    int len = hexStr.length()/2;
	    byte[] result = new byte[len];
	    char[] chars = hexStr.toCharArray();
	    for(int i=0;i<len;i++){
	        result[i] = (byte)(charToByte(chars[i])<<4 | charToByte(chars[i+1]));
	    }
	    return result;
	}

	private static int charToByte(char c) {
		String chars = "0123456789ABCDEF";
	    byte b = (byte)chars.indexOf(c);
	    return b;
	}

}